package com.khstudio.videocapture.khvideocapture;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;

import com.khstudio.api.util.KhLog;
import com.khstudio.api.view.KhImageBoxView;
import com.khstudio.api.view.VideoPlayButton_Kh;
import com.khstudio.videocapture.gl.SeekBarViewDemo;
import com.khstudio.videocapture.gl.SeekBarViewDemo.KhVideoSeekBarListener;

public class KhVideoCaptureControlGroup extends ViewGroup {
    private Context mContext;

    private boolean             isEnabled;

    private SeekBarViewDemo      mSeekBar;
    private VideoPlayButton_Kh       mBtnPlay;
    private Button                  mBtnSaveFrameSingle;
    private Button                  mBtnSaveFrameMulti;
    private KhImageBoxView          mRepositoryView;
    private ProgressBar             mProgress;

    private KhVideoCaptureControlGroupListener mListener;

    private int padding_left;
    private int padding_top;
    private int padding_right;
    private int padding_bottom;
    private int padding_btn_gap;

    private int show_btn_left_pos;
    private int show_seekbar_bottom_pos;
//    private class KEditControlLayout {
//        int LAYOUT_TOP_PADDING = 0;
//        int LAYOUT_LEFT_PADDING = 0;
//        int LAYOUT_RIGHT_PADDING = 0;
//        int BTN_GAP_PADDING = 0;
//
//        int BTN_SAVEFRAME_SINGLE_WIDTH = 0;
//        int BTN_SAVEFRAME_SINGLE_HEIGHT = 0;
//
//        int BTN_SAVEFRAME_MULTI_WIDTH = 0;
//        int BTN_SAVEFRAME_MULTI_HEIGHT = 0;
//
//        int BTN_REPOSITORY_WIDTH = 0;
//        int BTN_REPOSITORY_HEIGHT = 0;
//
//        int    SHOW_DELAY = 10;
//        long   SHOW_ROOP_TIME = 0;
//        double SHOW_SEEKBAR_BOTTOM_POS = 0;
//        double SHOW_BTN_LEFT_POS = 0;
//        float  SHOW_ALPHA = 1f;
//    }

    public interface KhVideoCaptureControlGroupListener {
        void onSingleSaveButtonClick(int time);
        void onMultiSaveButtonClick(int time);
        void onRepositoryButtonClick();
    }

    public KhVideoCaptureControlGroup(Context context) {
        this(context, null);
    }

    public KhVideoCaptureControlGroup(Context context, AttributeSet attrs) {
        this(context, attrs , 0);
    }

    public KhVideoCaptureControlGroup(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        mContext = context;
        mListener = null;

//        mState = STATE_SHOW;
        isEnabled = false;

//        setOnClickListener();

        createLayout();
        setAttribute(attrs,defStyle);
    }

    public void setOnKhVideoCaptureControlGroupListener(KhVideoCaptureControlGroupListener l) {
        mListener = l;
    }

    public void setOnClickListenerSaveSingle(OnClickListener l) {
        mBtnSaveFrameSingle.setOnClickListener(l);
        mBtnSaveFrameSingle.setVisibility(View.VISIBLE);
    }

    public void setOnClickListenerSaveMulti(OnClickListener l) {
        mBtnSaveFrameMulti.setOnClickListener(l);
        mBtnSaveFrameMulti.setVisibility(View.VISIBLE);
    }

    public void setOnClickListenerRepository(OnClickListener l) {
        mRepositoryView.setOnClickListener(l);
        mRepositoryView.setVisibility(View.VISIBLE);
    }

//    public void setOnClickListenerPlay(KhImageToggleViewListener l) {
//        mBtnPlay.setKhImageToggleViewListener(l);
//        mBtnPlay.setVisibility(View.VISIBLE);
//    }

    public void setOnVideoSeekBarListener(KhVideoSeekBarListener l) {
        mSeekBar.setOnVideoSeekBarListener(l);
        mSeekBar.setVisibility(View.VISIBLE);
    }

    public void setDuration(long duration) {
        mSeekBar.setDuration(duration);
    }

    public void setSeekBarThumbTime(long timeMs) {
        mSeekBar.setThumbTime(timeMs);
    }

    public void setSeekBarThumbTimeForce(long timeMs) {
        mSeekBar.setThumbTimeForce(timeMs);
    }

    public int getSeekBarThumbProgressGapTime() {
        return mSeekBar.getThumbProgressGapTime();
    }

//    public void setPlayButtonState(STATE s) {
//        mBtnPlay.setState(s);
//    }

    public void setRepositoryImage(Bitmap bm) {
        mRepositoryView.setImage(bm);
    }

    public void setGroupEnabled(boolean enable) {
        if(isEnabled == enable)
            return;

        isEnabled = enable;
        if(isEnabled) mProgress.setVisibility(View.GONE);
        else          mProgress.setVisibility(View.VISIBLE);

        mBtnSaveFrameSingle.setEnabled(isEnabled);
        mBtnSaveFrameMulti.setEnabled(isEnabled);
        mRepositoryView.setEnabled(isEnabled);
        mBtnPlay.setEnabled(isEnabled);
    }

    public boolean getGroupEnabled() { return isEnabled; }

    public Rect getEffectDstRect() {
        return mRepositoryView.getRectImage();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if(mSeekBar != null) {
            mSeekBar.measure(widthMeasureSpec, heightMeasureSpec);
        }

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int left = l;
        int top = t;
        int right = 0;
        int bottom = 0;

        left = padding_left;
        if (mBtnSaveFrameSingle.getVisibility() == View.VISIBLE) {
            top = padding_top;
            right = left + mBtnSaveFrameSingle.getBackground().getIntrinsicWidth() - show_btn_left_pos;
            bottom = top + mBtnSaveFrameSingle.getBackground().getIntrinsicHeight();
            mBtnSaveFrameSingle.layout(left, top, right, bottom);
        }

        if (mBtnSaveFrameMulti.getVisibility() == View.VISIBLE) {
            top = bottom + padding_btn_gap;
            right = left + mBtnSaveFrameMulti.getBackground().getIntrinsicWidth() - show_btn_left_pos;
            bottom = top + mBtnSaveFrameMulti.getBackground().getIntrinsicHeight();
            mBtnSaveFrameMulti.layout(left, top, right, bottom);
        }

        if (mRepositoryView.getVisibility() == View.VISIBLE) {
            top = bottom + padding_btn_gap;
            right = left + mRepositoryView.geWidthBox() - show_btn_left_pos;
            bottom = top + mRepositoryView.getHeightBox();
            mRepositoryView.layout(left, top, right, bottom);
        }

        if (mProgress.getVisibility() == View.VISIBLE) {
            top = bottom + padding_btn_gap;
            right = left + mRepositoryView.geWidthBox() - show_btn_left_pos;
            bottom = top + mRepositoryView.getHeightBox();
            mProgress.layout(left, top, right, bottom);
        }

        if (mBtnPlay.getVisibility() == View.VISIBLE) {
            left = (r - l - mBtnPlay.getDrawableWidth()) / 2;
            top = (b - t - mBtnPlay.getDrawableHeight()) / 2;
            right = left + mBtnPlay.getDrawableWidth();
            bottom = top + mBtnPlay.getDrawableHeight();
            mBtnPlay.layout(left, top, right, bottom);
        }

        if (mSeekBar.getVisibility() == View.VISIBLE) {
            left = l;
            right = left + mSeekBar.getMeasuredWidth();
            bottom = b - padding_bottom;
            top = bottom - mSeekBar.getMeasuredHeight() + (int) show_seekbar_bottom_pos;
            mSeekBar.layout(left, top, right, bottom);
        }
    }

    private void setAttribute(AttributeSet attrs, int defStyle) {
        int[] ids = new int[attrs.getAttributeCount()];
        for (int i = 0; i < attrs.getAttributeCount(); i++) {
            ids[i] = attrs.getAttributeNameResource(i);
        }

        TypedArray a = mContext.obtainStyledAttributes(attrs, ids, defStyle, 0);

        for (int i = 0; i < attrs.getAttributeCount(); i++) {
            String attrName = attrs.getAttributeName(i);
            if (attrName == null)
                continue;

            if (attrName.equals("control_left_padding")) {
                padding_left = a.getDimensionPixelSize(i, 0);
            } else if (attrName.equals("control_top_padding")) {
                padding_top = a.getDimensionPixelSize(i, 0);
            } else if (attrName.equals("control_right_padding")) {
                padding_right = a.getDimensionPixelSize(i, 0);
            } else if (attrName.equals("control_bottom_padding")) {
                padding_bottom = a.getDimensionPixelSize(i, 0);
            } else if (attrName.equals("control_btn_gap_padding")) {
                padding_btn_gap = a.getDimensionPixelSize(i, 0);
            } else if (attrName.equals("contorl_btn_save_single")) {
                mBtnSaveFrameSingle.setBackground(a.getDrawable(i));
            } else if (attrName.equals("contorl_btn_save_multi")) {
                mBtnSaveFrameMulti.setBackground(a.getDrawable(i));
            } else if (attrName.equals("contorl_btn_repository")) {
                mRepositoryView.setBaseDrawable(a.getDrawable(i));
            } else if (attrName.equals("contorl_btn_emptybox")) {
                mRepositoryView.setBoxDrawable(a.getDrawable(i));
//            } else if (attrName.equals("contorl_btn_play")) {
//                mBtnPlay.setDrawableOn(a.getDrawable(i));
//            } else if (attrName.equals("contorl_btn_pause")) {
//                mBtnPlay.setDrawableOff(a.getDrawable(i));
            }
        }

        a.recycle();
    }

    private void createLayout() {
        int typeValue = TypedValue.COMPLEX_UNIT_DIP;
        DisplayMetrics metrics = mContext.getResources().getDisplayMetrics();

        padding_left    = (int) TypedValue.applyDimension(typeValue, 10, metrics);
        padding_top     = (int) TypedValue.applyDimension(typeValue, 10, metrics);
        padding_right   = (int) TypedValue.applyDimension(typeValue, 10, metrics);
        padding_bottom  = (int) TypedValue.applyDimension(typeValue, 10, metrics);
        padding_btn_gap = (int) TypedValue.applyDimension(typeValue, 5, metrics);

        show_btn_left_pos = 0;

        mBtnSaveFrameSingle = new Button(mContext);
        mBtnSaveFrameSingle.setEnabled(false);
        mBtnSaveFrameSingle.setVisibility(View.GONE);
        addView(mBtnSaveFrameSingle);

        mBtnSaveFrameMulti = new Button(mContext);
        mBtnSaveFrameMulti.setEnabled(false);
        mBtnSaveFrameMulti.setVisibility(View.GONE);
        addView(mBtnSaveFrameMulti);

        mRepositoryView = new KhImageBoxView(mContext);
        mRepositoryView.setEnabled(false);
        mRepositoryView.setVisibility(View.GONE);
        addView(mRepositoryView);

        mProgress = new ProgressBar(mContext);
        mProgress.setVisibility(View.VISIBLE);
        addView(mProgress);

        mBtnPlay = new VideoPlayButton_Kh(mContext);
        mBtnPlay.setEnabled(false);
        mBtnPlay.setVisibility(View.GONE);
        // mBtnPlayPause.setOnClickListener(this);
        addView(mBtnPlay);

        mSeekBar = new SeekBarViewDemo(mContext);
        // mSeekBar.setSeekViewListener(this);
//        mSeekBar.setDuration(100000);
        mSeekBar.setVisibility(View.GONE);
        addView(mSeekBar);

    }

    private void singleSaveClick() {
        if(mListener != null) {
//            mListener.onSingleSaveButtonClick(mSeekBar.getThumbTime());
        } else {
            KhLog.w("singleSaveClick : mListener is null");
        }
    }

    private void multiSaveClick() {
        if(mListener != null) {
//            mListener.onMultiSaveButtonClick(mSeekBar.getThumbTime());
        } else {
            KhLog.w("singleSaveClick : mListener is null");
        }
    }

    private void repositoryClick() {
        if(mListener != null) {
            mListener.onRepositoryButtonClick();
        } else {
            KhLog.w("repositoryClick : mListener is null");
        }
    }

//    private final Handler mHandler = new Handler() {
//        @Override
//        public void handleMessage(Message msg) {
//            switch (msg.what) {
//                case HANDLER_SHOW_CONTROL:
//                    if(mState == STATE_SHOWING) {
//                        long loopTime = System.currentTimeMillis();
//                        long delay = loopTime - mLayout.SHOW_ROOP_TIME;
//                        mLayout.SHOW_ROOP_TIME = loopTime;
//
//                        mLayout.SHOW_SEEKBAR_BOTTOM_POS -= (double)mSeekBar.getMeasuredHeight() * (double)delay / (double)SHOW_DURARION;
//                        mLayout.SHOW_BTN_LEFT_POS       -= (double)(mLayout.LAYOUT_LEFT_PADDING + mLayout.BTN_SAVEFRAME_SINGLE_WIDTH) * (double)delay / (double)SHOW_DURARION;
//                        mLayout.SHOW_ALPHA              += (float)((double)delay / (double)SHOW_DURARION);
//
//                        if(mLayout.SHOW_SEEKBAR_BOTTOM_POS < 0 || mLayout.SHOW_BTN_LEFT_POS < 0 || mLayout.SHOW_ALPHA > 1) {
//                            mLayout.SHOW_SEEKBAR_BOTTOM_POS = 0;
//                            mLayout.SHOW_BTN_LEFT_POS = 0;
//                            mLayout.SHOW_ALPHA = 1f;
//
//                            mHandler.sendEmptyMessageDelayed(HANDLER_SHOW_CONTROL_DONE, mLayout.SHOW_DELAY);
//                        } else {
//                            mHandler.sendEmptyMessageDelayed(HANDLER_SHOW_CONTROL, mLayout.SHOW_DELAY);
//                        }
//
//                        setAlphaControl(mLayout.SHOW_ALPHA);
//                        mChangedLayout |= LAYOUT_UPDATE_CONTROL;
//                        requestLayout();
//                    }
//                    break;
//
//                case HANDLER_SHOW_CONTROL_DONE :
//                    if(mState == STATE_SHOWING) {
//                        mState = STATE_SHOW;
//                    }
//                    break;
//
//                case HANDLER_HIDE_CONTROL:
//                    if(mState == STATE_HIDING) {
//                        long loopTime = System.currentTimeMillis();
//                        double delay = loopTime - mLayout.SHOW_ROOP_TIME;
//                        mLayout.SHOW_ROOP_TIME = loopTime;
//
//                        mLayout.SHOW_SEEKBAR_BOTTOM_POS += (double)mSeekBar.getMeasuredHeight() * (double)delay / (double)SHOW_DURARION;
//                        mLayout.SHOW_BTN_LEFT_POS       += (double)(mLayout.LAYOUT_LEFT_PADDING + mLayout.BTN_SAVEFRAME_SINGLE_WIDTH) * (double)delay / (double)SHOW_DURARION;
//                        mLayout.SHOW_ALPHA              -= (float)((double)delay / (double)SHOW_DURARION);
//
//                        if(mLayout.SHOW_SEEKBAR_BOTTOM_POS > mSeekBar.getMeasuredHeight() ||
//                           mLayout.SHOW_BTN_LEFT_POS       > (mLayout.LAYOUT_LEFT_PADDING + mLayout.BTN_SAVEFRAME_SINGLE_WIDTH) ||
//                           mLayout.SHOW_ALPHA              < 0 ) {
//                            mLayout.SHOW_SEEKBAR_BOTTOM_POS = mSeekBar.getMeasuredHeight();
//                            mLayout.SHOW_BTN_LEFT_POS = mLayout.LAYOUT_LEFT_PADDING + mLayout.BTN_SAVEFRAME_SINGLE_WIDTH;
//                            mLayout.SHOW_ALPHA = 0f;
//
//                            mHandler.sendEmptyMessageDelayed(HANDLER_HIDE_CONTROL_DONE, mLayout.SHOW_DELAY);
//                        } else {
//                            mHandler.sendEmptyMessageDelayed(HANDLER_HIDE_CONTROL, mLayout.SHOW_DELAY);
//                        }
//
//                        setAlphaControl(mLayout.SHOW_ALPHA);
//                        mChangedLayout |= LAYOUT_UPDATE_CONTROL;
//                        requestLayout();
//                    }
//                    break;
//
//
//                case HANDLER_HIDE_CONTROL_DONE :
//                    if(mState == STATE_HIDING) {
//                        mState = STATE_HIDE;
//                    }
//                    break;
//
//                default:
//                    break;
//            }
//        }
//    };
//
//    private static final int STATE_SHOWING  = 0x0002;
//    private static final int STATE_SHOW     = 0x0003;
//    private static final int STATE_HIDING   = 0x0004;
//    private static final int STATE_HIDE     = 0x0005;
//
//    private static final int HANDLER_SHOW_CONTROL        = 0x0001;
//    private static final int HANDLER_SHOW_CONTROL_DONE   = 0x0002;
//    private static final int HANDLER_HIDE_CONTROL        = 0x0003;
//    private static final int HANDLER_HIDE_CONTROL_DONE   = 0x0004;
//
//    private int mState;
//    private static final int SHOW_DURARION = 300;
//
//    private void showhideControl() {
//        if(mState == STATE_HIDE || mState == STATE_HIDING) {
//            mState = STATE_SHOWING;
//            mLayout.SHOW_ROOP_TIME = System.currentTimeMillis();
//            mHandler.removeMessages(HANDLER_SHOW_CONTROL);
//            mHandler.sendEmptyMessageDelayed(HANDLER_SHOW_CONTROL, mLayout.SHOW_DELAY);
//        } else if(mState == STATE_SHOW || mState == STATE_SHOWING) {
//            mState = STATE_HIDING;
//            mLayout.SHOW_ROOP_TIME = System.currentTimeMillis();
//            mHandler.removeMessages(HANDLER_HIDE_CONTROL);
//            mHandler.sendEmptyMessageDelayed(HANDLER_HIDE_CONTROL, mLayout.SHOW_DELAY);
//        }
//    }
//
//    private void setAlphaControl(float alpha) {
//        mBtnSaveFrameMulti.setAlpha(alpha);
//        mBtnSaveFrameSingle.setAlpha(alpha);
//        mRepositoryView.setAlpha(alpha);
//        mBtnPlayPause.setAlpha(alpha);
//    }
}
